package com.luohuasheng.spring.boot.starter.core;

import org.springframework.util.ObjectUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认锁
 *
 * @author zl
 */
public class DefaultLockCache implements LockCache {

    /**
     * 显示锁集合  key,时间秒
     */
    private static final ConcurrentHashMap<String, LockEntity> lockMap = new ConcurrentHashMap<>();


    @Override
    public boolean lock(String key) {
        LockEntity entity = lockMap.get(key);
        if(!ObjectUtils.isEmpty(entity) && entity.hasOutTime()){
            lockMap.remove(key);
        }
        //如果同步集合中已经存在锁，则直接返回已经存在的锁
        Object val = lockMap.putIfAbsent(key,LockEntity.newInstance());
        return val == null;
    }

    @Override
    public void unLock(String key) {
       lockMap.remove(key);
    }


    /**
     * 锁定值
     */
    public static class LockEntity{

        /**
         * 过期时间 秒
         */
        private Integer second;

        /**
         * 创建时间 毫秒
         */
        private Long createAt;

        public Integer getSecond() {
            return second;
        }

        public void setSecond(Integer second) {
            this.second = second;
        }

        public Long getCreateAt() {
            return createAt;
        }

        public void setCreateAt(Long createAt) {
            this.createAt = createAt;
        }

        /**
         * 是否已经超时
         */
        public boolean hasOutTime(){
            Long nowTime = System.currentTimeMillis();
            return (nowTime - this.createAt) / 1000 > second;
        }

        public static LockEntity newInstance(){
            LockEntity entity =  new LockEntity();
            entity.setSecond(10);
            entity.setCreateAt(System.currentTimeMillis());
            return entity;
        }
    }
}
